package com.yima.baseproj.module.sys.login;

import com.yima.baseproj.aop.log.Logging;
import com.yima.baseproj.module.sys.login.model.LoginLoginModel;
import com.yima.baseproj.module.sys.user.SysUserService;
import com.yima.baseproj.security.SecurityUtil;
import com.yima.baseproj.security.annotation.SecurityIgnoreUrl;
import com.yima.baseproj.security.model.UserLoginAuthModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @Author 一码
 * @createDate 2023/4/1 09:00
 * @contact 1424529270@qq.com
 */
@Api(tags = "登录", value = "登录")
@RestController
@RequestMapping("/api/sys/login")
public class SysLoginController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Resource
    private SysUserService sysUserService;

    @Resource
    private SysLoginService sysLoginService;

    @Logging(tags = "登录管理",value = "登录")
    @SecurityIgnoreUrl
    @ApiOperation(value = "登录")
    @PostMapping(value = "/login")
    public String login(@Validated @RequestBody LoginLoginModel loginLoginModel) {
        return sysLoginService.login(loginLoginModel);
    }

    @Logging(tags = "登录管理",value = "登出")
    @ApiOperation(value = "登出")
    @PostMapping(value = "/logout")
    public void logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserLoginAuthModel userLoginAuthModel = (UserLoginAuthModel) authentication.getPrincipal();
        String userId = userLoginAuthModel.getUserId();
        String client = userLoginAuthModel.getClient();

        SecurityUtil.delTokenToRedis(client,userId);
    }
}